/*
 * @Author: taiyunhang
 * @Date: 2018-12-14 11:24:28
 * */

/**
 * 拦截器的配置
 */
import axios from 'axios';
// import qs from 'qs';
import router from '../routes';
import store from '@/store';
import { MessageBox, Toast } from 'mint-ui';
import LocalStorage from '@/services/storage';
import { requestCode } from '@/env';
import $ from 'jquery';
const proxy = require('@/env/proxy');
const proxyPath = proxy.proxyPath;
// 创建实例时设置配置的默认值
const guid=()=>{
  function S4() {
	  return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
	}
  return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
};
const service = axios.create({
  baseURL: proxyPath,
  /* headers: {
    'Content-Type': 'application/json; charset=UTF-8'
  }, */
  headers: {
    'Content-Type': 'application/json; charset=UTF-8',
    'Accept': 'application/json, text/javascript, */*; q=0.01',
  },
  responseType: 'json',
  timeout: 1000 * 60, // 请求超时的时间
  // 对响应的数据进行处理
  transformResponse: [
    function(data) {
      return data;
      // return JSON.parse(data);
    }
  ],
  // 对请求的数据进行处理
  transformRequest: [
    function(data) {
      let token = LocalStorage.getLocalStorage('token');
      // let loginStatus = LocalStorage.getLocalStorage('loginStatus');
      // data && (data["body"].sourceCode = sourceCode.sourceCode);
      data && token && (data["head"].token = token);
      // data && loginStatus && (data["body"].matrixContent = loginStatus);
      // return JSON.stringify(data);
      // return qs.stringify(data);
      if(!token){
        if(data.body && data.body.needToken){
        
            var _obj = {
              "body":{
                "data": token
              },
              "head":{
                "requestCode": requestCode,
                "serialno": guid()
              },
            };
            $.ajax({
              url:proxyPath+'user/login',//url路径
              type:'POST', //GET
              async:false, //或false,是否异步
              data:JSON.stringify(_obj),
              contentType:"application/json; charset=UTF-8",
              timeout:5000, //超时时间
              dataType:'json', //返回的数据格式：
              beforeSend:function(xhr){
              },
              success:function(res){
                if (res.head.resultCode == "000000") {
                  let token2 = res.head.token;
                  data["head"].token = token2
                  LocalStorage.setLocalStorage(
                    "token",
                    token2,
                    59 * 60 * 1000
                  );
                }
              },
              error:function(xhr,textStatus){
              },
              complete:function(data){
              }
          })


          // 
        }
        
      }
      return JSON.stringify(data);
    }
  ]
});

// 请求拦截器
service.interceptors.request.use(
  config => {
    store.dispatch('openLoading');
    return config;
  },
  err => {
    setTimeout(() => {
      store.dispatch('closeLoading');
    }, 50);
    Toast({ message: '加载超时', position: 'middle' });
    return Promise.reject(err);
  }
);

// 响应拦截器
service.interceptors.response.use(
  res => {
    if (res) {
      let data = res.data.head;
      console.log(data)
      // 非登录 -- 路由重定向
      if (data && data.resultCode && data.resultCode !== 'SUCCESS' && data.resultCode !== 'REFUND_SUCCESS') {
        setTimeout(() => {
          store.dispatch('closeLoading');
        }, 50);
        if (data.resultCode === '000001') {
          setTimeout(()=> {
            store.dispatch('logout');
            router.push('mainpage');
          },200)
          
        }
      }
    }
    return res;
  },
  err => {
    console.log(err);
    setTimeout(() => {
      store.dispatch('closeLoading');
    }, 50);
    if (err.response) {
      switch (err.response.status) {
        case 401:
          // 返回 401 清除token信息并跳转到登录页面
          store.dispatch('logout');
          router.replace({
            path: 'login',
            query: { redirect: router.currentRoute.fullPath }
          });
      }
    }
    Toast({ message: '服务器有事离开一下，马上就回来', position: 'middle' });
    return Promise.reject(err);
  }
);

export default service;
